import { defineStore } from "pinia";
import { store } from "@/store";
import { ref } from "vue";
import { HMI_PTST_API } from "@/api/hmi/ptst.api";
import type {
  PtstSettingsResponse,
  PtstSettingItem,
  PtstUpdateRequest,
  PtstUpdateResponse,
} from "@/api/hmi/ptst.api";

/**
 * PTST 数据和定值的一次二次设置 Store
 */
export const usePtstStore = defineStore("ptst", () => {
  // 响应式状态
  const ptstSettings = ref<PtstSettingItem[][]>([]);
  const isLoading = ref<boolean>(false);
  const isUpdating = ref<boolean>(false);
  const isReady = ref<boolean>(false);

  // 获取当前设置
  const getCurrentSettings = () => {
    if (ptstSettings.value.length === 0 || ptstSettings.value[0].length === 0) {
      return { data: 0, setting: 0 };
    }

    const firstArray = ptstSettings.value[0];
    const dataItem = firstArray.find((item) => item.Data !== undefined);
    const settingItem = firstArray.find((item) => item.Setting !== undefined);

    return {
      data: dataItem?.Data || 0,
      setting: settingItem?.Setting || 0,
    };
  };

  // 获取枚举选项
  const getEnumOptions = () => {
    if (ptstSettings.value.length === 0 || ptstSettings.value[0].length === 0) {
      return [];
    }

    const firstItem = ptstSettings.value[0][0];
    return firstItem?.FakeEnum || [];
  };

  // 设置函数
  const setPtstSettings = (settings: PtstSettingItem[][]) => {
    ptstSettings.value = settings;
    isReady.value = true;
  };

  // API 调用函数
  const fetchPtstSettings = (cpu: number) => {
    return new Promise<PtstSettingItem[][]>((resolve, reject) => {
      isLoading.value = true;
      HMI_PTST_API.fetchPtstSettings(cpu)
        .then((res) => {
          console.log("fetchPtstSettings res:", res);
          setPtstSettings(res);
          resolve(res);
        })
        .catch((error) => {
          console.error("fetchPtstSettings error:", error);
          reject(error);
        })
        .finally(() => {
          isLoading.value = false;
        });
    });
  };

  const updatePtstSettings = (cpu: number, data: PtstUpdateRequest[]) => {
    return new Promise<PtstUpdateResponse>((resolve, reject) => {
      isUpdating.value = true;
      HMI_PTST_API.updatePtstSettings(cpu, data)
        .then((res) => {
          // 更新成功后重新获取最新数据
          fetchPtstSettings(cpu).catch(() => {});
          resolve(res);
        })
        .catch((error) => {
          console.error("updatePtstSettings error:", error);
          reject(error);
        })
        .finally(() => {
          isUpdating.value = false;
        });
    });
  };

  // 更新数据设置
  const updateDataSetting = (cpu: number, dataValue: number) => {
    return updatePtstSettings(cpu, [{ Data: dataValue }]);
  };

  // 更新定值设置
  const updateSettingValue = (cpu: number, settingValue: number) => {
    return updatePtstSettings(cpu, [{ Setting: settingValue }]);
  };

  return {
    // 状态
    ptstSettings,
    isLoading,
    isUpdating,
    isReady,

    // 计算属性
    getCurrentSettings,
    getEnumOptions,

    // 设置函数
    setPtstSettings,

    // API 调用函数
    fetchPtstSettings,
    updatePtstSettings,
    updateDataSetting,
    updateSettingValue,
  };
});

/**
 * 适用于 setup 之外的场景
 */
export function usePtstStoreHook() {
  return usePtstStore(store);
}
